<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Goods extends Auth_Controller {
    public function __construct()
    {

        parent::__construct();
        $this->load->model('goods_model', 'goods');
        $this->load->model('user_model', 'user');
        $this->load->model('address_model', 'address');
    }
    /**
     *------------------------------------------------------------------------------------------------------------------
     * @title：根据分类id获取产品列表
     * @action：/Item/index.json
     * @method：GET
     * @param：cat_id             类型：INT，必须：YES ，描述：分类id
     * @author:：KevinBai
     *------------------------------------------------------------------------------------------------------------------
     */
    public function index()
    {
        $limit = $this->config->item('limit');
        $this->isArrays = true;
        $params['per_page'] = $this->queryData['per_page'] ? $this->queryData['per_page'] : 1;
        $validate = new Validate([
            'per_page' => 'require|number',
        ]);
        if (!$validate->check($params)) {
            $this->errorCode = 50003;
            $this->errorMessage = $validate->getError();
            $this->createApi();
            exit;
        }
        $fields = " id, title, price, exchangepoints, summary,stock ";
        $goodsList = $this->goods->get_goods_list($fields, $params['per_page'],$limit);
        foreach ($goodsList as $key => $value) {
            $goodsList[$key]['summary'] = cutstr(strip_tags($goodsList[$key]['summary']),30);
            $imgurl = $this->goods->get_default_cover($value['id']);
            $goodsList[$key]['imgurl'] = $imgurl ? OSSHOST.$imgurl : "";
        }
        
        $this->createApi($goodsList);
    }


  
    public function detail(){
        $params['id'] = $this->queryData['id'];
        $validate = new Validate([
            'id' => 'require|number',
        ]);
        if (!$validate->check($params)) {
            $this->errorCode = 50003;
            $this->errorMessage = $validate->getError();
            $this->createApi();
            exit;
        }

        $goodsInfo = $this->goods->get_goods_by_id($params['id'], " * ");
        unset($goodsInfo['isDel']);
        unset($goodsInfo['onlinestatus']);
        unset($goodsInfo['addtime']);
        //获取产品封面轮播图
        $goodsCover = $this->goods->get_img_list_byid($params['id'], "imgurl");
        if($goodsCover){
            foreach ($goodsCover as $key => $value) {
                $goodsCover[$key]['imgurl'] = $value['imgurl'] ? OSSHOST.$value['imgurl'] : "";
            }
        }
        if(!empty($goodsInfo)){
            $goodsInfo['cover'] = $goodsCover;
        }
        $userInfo = $this->userDetail;
        $goodsInfo['myPoints'] = 0;
        if($userInfo){
            $goodsInfo['myPoints'] = $userInfo['points'];
        }
        
        $this->createApi($goodsInfo);
    }
   



    /**
     *------------------------------------------------------------------------------------------------------------------
     * @title：对产品添加收藏，取消收藏
     * @action：/dynamic/doCollect
     * @param  $status 1:取消收藏，2：添加收藏
     * @method：POST
     * @author:：柏凯
     * @date：2015-11-14
     *------------------------------------------------------------------------------------------------------------------
     */
    public function setCollect(){
        $this->check_login_status();
        $itemid = $this->json_content['itemid'];
        $token = $this->json_content['token']?$this->json_content['token']:0;
        if(empty($itemid)){
            $this->errorCode = API_ERROR_PARAMS_MISS;
            $this->createApi();exit;
        }
        $userInfo = $this->userInfo($token);
        $fromUsername = $userInfo['Username'];
        $data = array(
                'typeid'=>$itemid,
                'fromUsername'=>$fromUsername,
                'createtime'=>time(),
                'type'=>2
                );
        $res = $this->item->setCollect($data);
        if($res === 'hasCollected'){
            $this->errorCode = API_ERROR_HASCOLLECTED;
        }
        elseif(!$res){
            $this->errorCode = API_ERROR_DATA_FALSE;
        }
        $this->createApi();
    }


    public function orderList(){
        $per_page = $this->queryData['per_page']?$this->queryData['per_page']:1;
        $limit  = $this->config->item('limit');
        $this->isArrays = true;
        $orderList = array();
        $userInfo = $this->userDetail;
        $orderList = $this->goods->getOrderList($userInfo['AccountID'],$per_page, $limit, " id,AccountID,goodsID,goodsName,exchangepoints,ordernum,status,receiver,mobile,area,createtime,goodsimgurl,expressName,expressNo");
        foreach ($orderList as $key => $value) {
            $orderList[$key]['createtime'] = date("Y-m-d H:i:s", $value['createtime']);
            $orderList[$key]['goodsimgurl'] =$orderList[$key]['goodsimgurl']?OSSHOST.$orderList[$key]['goodsimgurl']:""; 
        }
        $this->createApi($orderList);
    }

    public function delOrder(){
        $params['orderId'] = $this->queryData['orderId'];
        $validate = new Validate([
            'orderId' => 'require|number',
        ]);
        if (!$validate->check($params)) {
            $this->errorCode = 50003;
            $this->errorMessage = $validate->getError();
            $this->createApi();
            exit;
        }
        $userInfo = $this->userDetail;
        $result = $this->goods->delOrder($params['orderId'], $userInfo['AccountID']);
        $this->createApi();
    }

    /**
     *------------------------------------------------------------------------------------------------------------------
     * @title：确认订单页面
     * @action：/Goods/order
     * @method：POST
     * @author:：柏凯
     *------------------------------------------------------------------------------------------------------------------
     */
    public function order(){
		
		//根据id获取商品信息
        $params['goodsid'] = $this->queryData['goodsid'];;
        $validate = new Validate([
            'goodsid' => 'require|number',
        ]);
        if (!$validate->check($params)) {
            $this->errorCode = 50003;
            $this->errorMessage = $validate->getError();
            $this->createApi();
            exit;
        }
		
        $userInfo = $this->userDetail;
        //获取默认地址
        $default_address = array();
        $default_address = $this->address->address_get_default($userInfo['AccountID']," id,area,AccountID,isDefault,mobile,receiver  ");
		if(empty($default_address))
		{
			$this->errorCode = 90005;
            $this->createApi();exit;
		}
        $goodsInfo = $this->goods->get_goods_by_id($params['goodsid'], " id,title,price,exchangepoints ");
		if(empty($goodsInfo))
		{
			$this->errorCode = 90003;
            $this->createApi();exit;
		}
        
        //获取默认图片
        $imgurl = $this->goods->get_default_cover($params['goodsid']);
        $goodsInfo['cover'] = $imgurl ? OSSHOST.$imgurl : "";
        
        $result = array(
            'address'=>$default_address,
            'goodsInfo'=>$goodsInfo,
            'ordernum'=>generate_ordersn()
            );
        $this->createApi($result);

    }

    public function orderDetail(){
        
        //根据id获取商品信息
        $params['id'] = $this->queryData['id'];;
        $validate = new Validate([
            'id' => 'require|number',
        ]);
        if (!$validate->check($params)) {
            $this->errorCode = 50003;
            $this->errorMessage = $validate->getError();
            $this->createApi();
            exit;
        }
        
        $userInfo = $this->userDetail;
        //获取默认地址

        $orderDetail = $this->goods->getOrderDetail($params['id'],$userInfo['AccountID']);
        if($orderDetail)
        {
            $orderDetail['goodsimgurl'] = $orderDetail['goodsimgurl'] ? OSSHOST.$orderDetail['goodsimgurl'] : "";
        }
        $this->createApi($orderDetail);

    }

     /**
     *------------------------------------------------------------------------------------------------------------------
     * @title：提交订单
     * @action：/Goods/order
     * @method：POST
     * @author:：柏凯
     *------------------------------------------------------------------------------------------------------------------
     */
    public function submit(){
        $params['addressid'] = $this->queryData['addressid'];
        $params['ordernum'] = $this->queryData['ordernum'];
        $params['goodsid'] = $this->queryData['goodsid'];
        $validate = new Validate([
            'addressid' => 'require|number',
            'ordernum' => 'require|string',
            'goodsid' => 'require|number',
        ]);
        if (!$validate->check($params)) {
            $this->errorCode = 50003;
            $this->errorMessage = $validate->getError();
            $this->createApi();
            exit;
        }
		$orderInfo = $this->goods->orderInfoByOrdernum($params['ordernum']);
		if(!empty($orderInfo))
		{
			$this->errorCode = 90006;
            $this->createApi();
            exit;
		}
        $userInfo = $this->userDetail;
        $addressInfo = $this->address->address_detail($params['addressid'],"*",$userInfo['AccountID']);
        if(empty($addressInfo)){
            $this->errorCode = 90002;
            $this->createApi();exit;
        }
        $fields = " id, name ,pid ";
        $data = array();
        $goodsDate['receiver'] = $addressInfo['receiver'];
        $goodsDate['area'] = $addressInfo['area'];
        $goodsDate['mobile'] = $addressInfo['mobile'];
		$goodsDate['provincename'] = $this->address->getRegionById($addressInfo['provinceid'],'name')['name'];
		$goodsDate['cityname'] =  $this->address->getRegionById($addressInfo['cityid'],'name')['name'];
        $goodsInfo = $this->goods->get_goods_by_id($params['goodsid'], " id,title,price,exchangepoints,stock ");
        $goodsAttach = $this->goods->get_img_list_byid($params['goodsid']," imgurl ");

        if(empty($goodsInfo)){
            $this->errorCode = 90003;
            $this->createApi();exit;
        }
        if($goodsInfo['stock']<=0){
            $this->errorCode = 90008;
            $this->createApi();exit;
        }
        
        if($userInfo['points'] < $goodsInfo['exchangepoints']){
            $this->errorCode = 90004;
            $this->createApi();exit;
        }

        $res = $this->goods->minsPoints($userInfo['AccountID'],array("points"=>($userInfo['points']-$goodsInfo['exchangepoints'])));
        if($res)
		{
			//添加兑换金币记录
			$this->load->model('point_model', 'point');
			$data = array(
				'AccountID'=>$userInfo['AccountID'],
				'createtime'=>date('Y-m-d',time()),
				'points'=>($goodsInfo['exchangepoints']*(-1)),
				'type'=>10,
				'typeid'=>$params['goodsid'],
            );
			$res = $this->point->setPoints($data);
		}

        //获取默认图片
       // $imgurl = $this->goods->get_default_cover($id);
        $goodsDate['goodsID'] = $goodsInfo['id'];
        $goodsDate['goodsName'] = $goodsInfo['title'];
        $goodsDate['exchangepoints'] = $goodsInfo['exchangepoints'];
        $goodsDate['goodsimgurl'] = $goodsAttach[0]['imgurl']?$goodsAttach[0]['imgurl']:"";
        
        $goodsDate['ordernum'] = $params['ordernum'];
        $goodsDate['AccountID'] = $userInfo['AccountID'];
        $goodsDate['createtime'] = time();
        $res = $this->goods->submit($goodsDate);
		$this->goods->editGoodsStock($goodsInfo['id']);
        $this->createApi(array("exchangepoints"=>$goodsInfo['exchangepoints'],"goodsName"=>$goodsInfo['title'],"ordernum"=>$params['ordernum']));

    }

	

}

/* End of file category.php */
/* Location: ./application/controllers/luckydog/category.php */
